package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
   @Autowired
   private TaskinfoMapper taskinfoMapper;

   @Autowired
   private TaskinfoLogsMapper taskinfoLogsMapper;

   @Autowired
   private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    @Transactional
    public long addTask(Task task) {
        //1. 添加数据到数据库
        boolean flag = addDataToDB(task);

        //2. 如果数据库添加成功则添加任务到redis
        if(flag){
            addDataToRedis(task);
        }

        //3. 返回任务的id
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    @Transactional
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        //1. 更新数据库的数据
        Task task = updateDB(taskId, ScheduleConstants.CANCELLED);
        
        //2. 删除redis的缓存数据
        if(null != task){
            removeTaskFromRedis(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        //1. 构建redis的key
        String key = ScheduleConstants.TOPIC + "_" + type + "_" + priority;

        //2. 通过key获取到一个任务
        String json = cacheService.lRightPop(key);

        //3. 判断任务是否为空 如果不为空则 删除任务表更新日志表的状态
        if(StringUtils.isNotEmpty(json)){
            Task task = JSON.parseObject(json, Task.class);
            updateDB(task.getTaskId(), ScheduleConstants.EXECUTED);

            return task;
        }

        //4. 返回任务信息
        return null;
    }

    /**
     * 删除redis的缓存数据
     * @param task
     */
    private void removeTaskFromRedis(Task task) {
        //如果任务的执行时间到了 则删除list结合
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            String key = ScheduleConstants.TOPIC + "_" + task.getTaskType() + "_" + task.getPriority();
            cacheService.lRemove(key, 0, JSON.toJSONString(task));
        }else{
            //删除zset集合
            String key = ScheduleConstants.FUTURE + "_" + task.getTaskType() + "_" + task.getPriority();
            cacheService.zRemove(key, JSON.toJSONString(task));
        }
    }

    /**
     * 取消和消费任务的时候更新任务
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDB(long taskId, int status) {
        //1. 根据任务id删除任务数据
        taskinfoMapper.deleteById(taskId);

        //2. 更新任务日志的状态并返回Task对象
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        return task;
    }


    /**
     * 添加任务到redis
     * @param task
     */
    private void addDataToRedis(Task task) {
        //0. 获取未来5分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long futureTime = calendar.getTime().getTime();

        //1. 判断执行的时间\
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            //2. 构建redis的key
            String key = ScheduleConstants.TOPIC + "_" + task.getTaskType() + "_" + task.getPriority();
            //3. 添加数据
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= futureTime){
            String key = ScheduleConstants.FUTURE + "_" + task.getTaskType() + "_" + task.getPriority();
            cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库
     * @param task
     * @return
     */
    private boolean addDataToDB(Task task) {
        boolean flag = true;

        try {
            //保存任务
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task, taskinfoLogs);
            taskinfoLogs.setTaskId(taskinfo.getTaskId());
            taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            //把任务的id写回task
            task.setTaskId(taskinfo.getTaskId());
        } catch (Exception e){
            e.printStackTrace();
            flag = false;
        }

        return flag;
    }

    /**
     * @PostConstruct 初始化对象
     *  他会在spring创建完了该对象以后就调用这个方法来完成对象的初始化
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        //0. 添加分布式锁
        String value = cacheService.tryLock("FUTURE_TASK_SYNC", 30);
        if(StringUtils.isNotEmpty(value)){
            //1. 找到所有的future_的key
            Set<String> keys = cacheService.scan("future_*");

            //2. 判断key是否为空 如果不为空 则遍历每一个key(每一个key都表示一个结合)
            if(null != keys && keys.size() > 0){
                for (String key : keys) {
                    //3. 找到每一个key中过期的任务
                    Set<String> taskKeys = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
                    if(null != taskKeys && taskKeys.size() > 0){
                        //4. 把过期的任务从zset集合拷贝到list集合并删除zset集合中已经拷贝过的数据
                        // key: future_1_10 --> list: topic_1_10 key.split(ScheduleConstants.FUTURE) -->[future_,1_10]
                        String topicKey = ScheduleConstants.TOPIC + key.split(ScheduleConstants.FUTURE)[1];
                        cacheService.refreshWithPipeline(key,topicKey,taskKeys);
                        log.info("成功的将"+key+"刷新到了"+topicKey);
                    }
                }
            }

            //释放分布式锁
            cacheService.realseLock("FUTURE_TASK_SYNC");
        }

    }

    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData(){
        //1. 为了避免redis中的数据重复 需要删除list和zset中的数据
        clearCache();

        //2. 获取未来5分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //3. 查询执行时间小于等于未来5分钟的任务
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));

        //4. 判断是否查询到了任务 如果查询到了 则遍历每个任务并添加到redis中
        if(null != taskinfoList && taskinfoList.size() > 0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addDataToRedis(task);
            }
        }
    }

    private void clearCache() {
        Set<String> topicList = cacheService.scan("topic_*");
        Set<String> futureList = cacheService.scan("future_*");
        cacheService.delete(topicList);
        cacheService.delete(futureList);
    }
}
